$(function () {
    initArtCateList()

    function initArtCateList() {
        $.ajax({
            type: 'GET',
            url: '/my/article/cates',
            success: function (res) {
                if (res.status !== 0) return layui.layer.msg('获取图书列表失败！')
                var htmlStl = template('tpl-table', res)

                $('tbody').html(htmlStl)
            }
        })
    }


    var indexAdd = null;
    $('#btnAddCate').on('click', function () {
        indexAdd = layui.layer.open({
            type: 1,
            area: ['500px', '250px'], //['宽','高']
            title: '添加文章分类',
            content: $('#dialog-add').html()
        })
    })


    // 动态添加的form无法绑定事件
    $('body').on('submit', '#form-add', function (e) {
        e.preventDefault()

        $.ajax({
            type: 'POST',
            url: '/my/article/addcates',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) return layui.layer.msg('添加失败！')
                layui.layer.msg('添加成功！')

                initArtCateList()

                layui.layer.close(indexAdd)

            }
        })
    })

    var indexEdit = null;
    $('tbody').on('click', '.btn-edit', function () {
        // 弹出修改文章提示框
        indexEdit = layui.layer.open({
            type: 1,
            area: ['500px', '250px'], //['宽','高']
            title: '修改文章分类',
            content: $('#dialog-edit').html()
        })


        var id = $(this).attr('data-id');
        console.log(id);
        $.ajax({
            type: 'GET',
            url: '/my/article/cates/' + id,
            success: function (res) {
                if (res.status !== 0) return layui.layer.msg('获取失败!')
                layui.form.val('form-edit', res.data)
            }
        })
    })


    $('body').on('submit', '#form-edit', function (e) {
        e.preventDefault()
        $.ajax({
            type: 'POST',
            url: '/my/article/updatecate',
            data: $(this).serialize(),
            success: function (res) {
                console.log(res);
                if (res.status !== 0) return layui.layer.msg('修改失败！')
                layui.layer.msg('修改成功！')
                layui.layer.close(indexEdit);
                initArtCateList()
            }
        })
    })


    $('tbody').on('click', '.btn-delete', function () {
        var id = $(this).attr('data-id');
        layui.layer.confirm('确认删除', {
            icon: 3,
            title: '提示'
        }, function (index) {
            $.ajax({
                type: 'GET',
                url: '/my/article/deletecate/' + id,
                success: function (res) {
                    if (res.status !== 0) return layui.layer.msg('删除失败！')
                    layui.layer.msg('删除成功！')
                    layui.layer.close(index);
                    initArtCateList()
                }
            })
        })
    })


})